package com.daiyang.blog.common.advice;

import com.daiyang.blog.common.exception.BlogException;
import com.daiyang.blog.common.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.method.annotation.HandlerMethodValidationException;

@ControllerAdvice
@ResponseBody
@Slf4j
public class ExceptionAdvice {
    @ExceptionHandler
    public Result handleException(Exception e) {
        log.error("发生异常{}", e);
        return Result.resultError(e.getMessage());
    }
    @ExceptionHandler
    public Result handleException(BlogException e) {
        log.error("发生异常{}", e);
        return Result.resultError(e.getMsg());
    }
//    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
//    @ExceptionHandler({HandlerMethodValidationException.class,
//            MethodArgumentNotValidException.class})
//    public Result verifyHandle(Exception e){
//        log.error("参数校验失败: {}", e.getMessage());
//        return Result.resultError("参数校验失败 ");
//    }
    @ExceptionHandler
    public Result handleException(MethodArgumentNotValidException e) {
        log.error("参数校验失败: {}", e.getMessage());
        String msg = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
        return Result.resultError(msg);

    }
}
